/**
 * Created by easezhi on 2015/3/31.
 */
var Conn = require('../utils/Table').Table;
var debug = require('debug')('MODEL--ORDER: ');

/*登录用户查询个人订单
* 分页，默认每页10条
* 排序，默认按照生成时间倒序
* 订单状态
* 评价状态
* */
exports.myOrders = function(params ,callback){
    if(params.uid){
        var uid = params.uid;
        var idToken = 'userid';
    }else{
        var uid = params.carrierid;
        var idToken = 'carrierid';
    }
    var page = params.page;
    var rows = params.rows;
    var limit = (page-1)*rows;
    if(params.status == 2){
        var status = [2,5];
    }else{
        var status = [3];
    }
    var sql = "select i.id as id,orderno,i.userid as userid,i.username as username,i.phone as phone"
            +",i.type as type,carnum,num,picpath,startstation,endstation,"
            +"DATE_FORMAT(b.starttime,'%Y-%m-%d %T') as starttime ,DATE_FORMAT(b.endtime,'%Y-%m-%d %T') as endtime "
            +" ,status,DATE_FORMAT(i.createtime,'%Y-%m-%d %T') as createtime,b.price as price,advicestate "

            +",c.contact as contact,c.contactnum as contactnum"

            +" from information i,bid b,users c where i.id=b.inforid and i.carrierid=c.id  and i.carrierid=b.carrierid and status in (?)"
            +" and "+idToken+"=? order by status , i.createtime desc limit ?,?";
    var args = [status ,uid ,limit ,rows];
    var countSql = 'select count(*) as total from information where status in (?) and '+idToken+'=?'
    new Conn().getConnection(function(conn){
        var countQuery = conn.query(countSql ,args ,function(err ,rows){
            if(err){
                callback(err);
            }else{
                var total = rows[0].total;//订单总数

                var query = conn.query(sql ,args ,function(err ,rows){
                    if(err){
                        debug(err);
                        callback(err);
                    }else{
                        callback(null ,{
                            total:total
                            ,rows:rows
                        })
                    }

                    console.log(query.sql);
                    conn.release();//关闭mysql连接
                })
            }
        })
    })
}

/*根据订单id查询订单详情，包括发车人、承运人信息*/
exports.orderDetail = function(params ,callback){
    var sql = "select o.id,o.orderno as orderno,type,carnum,num,picpath,startstation,endstation"
        +",username,o.phone,status,DATE_FORMAT(o.createtime,'%Y-%m-%d %T') as createtime,o.userid,o.carrierid ,advicestate"

        +",u.phone as uphone,u.headerpath as uheaderpath"

        +",c.phone as cphone,c.company,c.headerpath as cheaderpath,c.contact as ccontact,c.contactnum as ccontactnum,DATE_FORMAT(c.createtime,'%Y-%m-%d %T') as ccreatetime,c.authstate,c.address,c.introduce"
        +",c.licences,c.roadlicences,c.attitude cattitude,c.care ccare,c.corresponds ccorresponds,c.evaluationnum"

        +",e.attitude,e.care,e.corresponds,evaluation,DATE_FORMAT(e.createtime,'%Y-%m-%d %T') as ecreatetime"

        +",b.price as price,accept,DATE_FORMAT(b.starttime,'%Y-%m-%d %T') as starttime,DATE_FORMAT(b.endtime,'%Y-%m-%d %T') as endtime"

        +" from information o LEFT JOIN users u on o.userid=u.id LEFT JOIN users c on o.carrierid=c.id join bid b on o.id=b.inforid "
        +" left join evaluation e on o.id=e.inforid where o.id=?";
    var args = [Number(params.id)];
    new Conn().getConnection(function(conn){
        conn.query(sql ,args ,function(err ,rows){
            if(err){
                callback(err);
            }else{
                var data = rows[0];
                var carnums = data.carnum.split(',');
                var nums = data.num.split(',');
                var pics = data.picpath.split(',')
                var count = 0;
                var carList = [];
                if(data.type == 1){
                    for(var x in carnums){
                        carnums[x] = Number(carnums[x]);
                        nums[x] = Number(nums[x]);
                        count += nums[x];
                        carList[x] = {
                            carnum:carnums[x]
                            ,num:nums[x]
                            ,pic:pics[x]
                        };
                    }
                }else{
                    for(var x in carnums){
                        carnums[x] = Number(carnums[x]);
                    }
                }
                var sql1 = "select carnum.id,num,carbrand from carnum LEFT JOIN carbrand on cbid=carbrand.id where carnum.id in (?)";
                var args1 = [carnums];
                conn.query(sql1 ,args1 ,function(err ,rows){
                    conn.release();
                    if(err){

                    }else{
                        if(data.type == 1){
                            for(var x in rows){
                                var car = rows[x];
                                for(var y in carList){
                                    if(carList[y].carnum == car.id){
                                        carList[y].type=car.num;
                                        carList[y].brand=car.carbrand;
                                    }
                                }
                            }
                        }

                        var order = {
                            id:data.id,orderno:data.orderno,type:data.type,cars:carList,carnums:carnums,nums:nums,total:count,picpath:data.picpath
                                ,startstation:data.startstation,endstation:data.endstation,starttime:data.starttime,endtime:data.endtime
                                ,username:data.username,phone:data.phone,status:data.status,createtime:data.createtime,price:data.price
                                ,advicestate:data.advicestate,accept:data.accept

                            ,user:{id:data.userid,phone:data.uphone,headerpath:data.uheaderpath}

                            ,carrier:{id:data.carrierid,phone:data.cphone,company:data.company,headerpath:data.cheaderpath,contact:data.ccontact,tel:data.ccontactnum,createtime:data.ccreatetime
                                ,authstate:data.authstate,address:data.address,introduce:data.introduce,licences:data.licences,roadlicences:data.roadlicences
                                ,attitude:data.cattitude,care:data.ccare,corresponds:data.ccorresponds,evaluationnum:data.evaluationnum
                            }
                            ,comment:{
                                inforid:data.id,attitude:data.attitude,care:data.care,corresponds:data.corresponds
                                ,evaluation:data.evaluation,createtime:data.ecreatetime
                            }
                        }
                        callback(null ,order);
                    }
                })
            }
        })
    })
}

/*取消订单*/
exports.cancelOrder = function(id ,callback){
    new Conn().getConnection(function(conn){
        var sql = "update information set status=5 where id=?";
        var args = [id];
        conn.query(sql ,args ,function(err ,data){
            if(err){
                callback(err)
            }else{
                callback(null ,data);
            }
        })
    })
}

/*保存服务评价*/
exports.saveComment = function(comment ,callback){
    new Conn('evaluation').insert(comment ,function(err ,data){
        if(err){
            callback({err:'err'})
        }else{
            new Conn().getConnection(function(conn){
                var sql = "update information set status=3 where id=?";
                var args = [comment.inforid];
                conn.query(sql ,args ,function(err ,data){
                    if(err){
                        callback({err:'err'})
                    }else{
                        var sql = "update users set attitude=(attitude+?),care=(care+?),corresponds=(corresponds+?),evaluationnum=(evaluationnum+1) where id=?";
                        var args = [comment.attitude ,comment.care ,comment.corresponds ,comment.carrierid];
                        conn.query(sql ,args ,function(err ,data){
                            if(err){

                            }else{
                                callback(null ,{status:'success'});
                            }
                        })

                    }
                })
            })
        }
    })
}

/*提交评价*/
exports.saveSuggest = function(suggest ,callback){
    new Conn('advice').insert(suggest ,function(err ,data){
        if(err){
            callback(err);
        }else{
            callback(null ,{status:'success'})
        }
    })
}

/*保存认证资料*/
exports.updateUserInfo = function(value ,callback){
    new Conn('users').update('id' ,value ,function(err ,data){
        callback(err ,data);
    })
}

/*承运方查询报价*/
exports.myBid = function(params ,callback){
    var carrierid = params.carrierid;
    var accept = params.accept;
    var page = params.page;
    var rows = params.rows;
    var limit = (page-1)*rows;
    var sql = "select b.id bid,b.price price,b.inforid id"
        +",DATE_FORMAT(b.starttime,'%Y-%m-%d %T') as bstart,DATE_FORMAT(b.endtime,'%Y-%m-%d %T') as bend"

        +",i.id as inforid,i.userid as userid,i.status as status,type,carnum,num,picpath,startstation as `from`,endstation dest,username,phone,DATE_FORMAT(b.createtime,'%Y-%m-%d %T') as createtime"

        +" from bid b,information i where b.inforid=i.id and b.carrierid=? and accept=0"
        +" order by i.status, b.createtime desc limit ?,?";
    var args = [carrierid ,limit ,rows];
    var countSql = "select count(*) total from bid where carrierid=? and accept=0";
    new Conn().getConnection(function(conn){
        var countQuery = conn.query(countSql ,args ,function(err ,rows){
            if(err){
                debug(err);
                callback(err);
            }else{
                var total = rows[0].total;//订单总数

                var query = conn.query(sql ,args ,function(err ,rows){
                    if(err){
                        debug(err);
                        callback(err);
                    }else{
                        callback(null ,{
                            total:total
                            ,rows:rows
                        })
                    }

                    debug(query.sql);
                    conn.release();//关闭mysql连接
                })
            }
        })
    })
}

/*承运方订单列表*/
exports.carrierOrders = function(params ,callback){
    var carrierid = params.carrierid;
    //var accept = params.accept;
    var status = params.status;
    if(status == 2){
        status = [2,5];
    }else{
        status = [3];
    }
    var page = params.page;
    var rows = params.rows;
    var limit = (page-1)*rows;
    var sql = "select b.id bid,b.price price,b.inforid id,accept"
        +",DATE_FORMAT(b.starttime,'%Y-%m-%d %T') as bstart,DATE_FORMAT(b.endtime,'%Y-%m-%d %T') as bend"

        +",i.id as inforid,orderno,i.userid as userid,i.status as status,type,carnum,num,picpath,startstation as `from`,endstation dest,username,phone,DATE_FORMAT(b.createtime,'%Y-%m-%d %T') as createtime"

        +" from bid b,information i where b.inforid=i.id and b.carrierid=? and i.status in(?) and accept=1"
        +" order by i.status, b.createtime desc limit ?,?";
    var args = [carrierid ,status,limit ,rows];
    var countSql = "select count(*) total from bid b,information i where b.inforid=i.id and  b.carrierid=? and i.status in(?) and accept=1";
    new Conn().getConnection(function(conn){
        var countQuery = conn.query(countSql ,args ,function(err ,rows){
            if(err){
                debug(err);
                callback(err);
            }else{
                var total = rows[0].total;//订单总数

                var query = conn.query(sql ,args ,function(err ,rows){
                    if(err){
                        debug(err);
                        callback(err);
                    }else{
                        callback(null ,{
                            total:total
                            ,rows:rows
                        })
                    }

                    debug(query.sql);
                    conn.release();//关闭mysql连接
                })
            }
        })
    })
}

/*承运方订单详情*/
exports.carrierOrderDetail = function(params ,callback){
    var sql = "select o.id,o.orderno as orderno,type,carnum,num,picpath,startstation,endstation"
        +",username,o.phone,status,DATE_FORMAT(o.createtime,'%Y-%m-%d %T') as createtime,o.userid,o.carrierid ,advicestate"

        +",u.phone as uphone,u.headerpath as uheaderpath"

        +",c.phone as cphone,c.company as ccompany,c.headerpath as cheaderpath,DATE_FORMAT(c.createtime,'%Y-%m-%d %T') as ccreatetime,c.carrierauthstate,c.address,c.introduce"
        +",c.licences,c.roadlicences,c.attitude cattitude,c.care ccare,c.corresponds ccorresponds,c.evaluationnum"

        +",e.attitude,e.care,e.corresponds,evaluation,DATE_FORMAT(e.createtime,'%Y-%m-%d %T') as ecreatetime"

        +",b.price as price,accept,DATE_FORMAT(b.starttime,'%Y-%m-%d %T') as starttime,DATE_FORMAT(b.endtime,'%Y-%m-%d %T') as endtime"

        +" from information o LEFT JOIN users u on o.userid=u.id LEFT JOIN users c on o.carrierid=c.id join bid b on o.id=b.inforid "
        +" left join evaluation e on o.id=e.inforid where o.id=?";
    var args = [Number(params.id)];
    new Conn().getConnection(function(conn){
        conn.query(sql ,args ,function(err ,rows){
            if(err){
                debug(err)
                callback(err);
            }else{
                var data = rows[0];
                var carnums = data.carnum.split(',');
                var nums = data.num.split(',');
                var pics = data.picpath.split(',')
                var count = 0;
                var carList = [];
                if(data.type == 1){
                    for(var x in carnums){
                        carnums[x] = Number(carnums[x]);
                        nums[x] = Number(nums[x]);
                        count += nums[x];
                        carList[x] = {
                            carnum:carnums[x]
                            ,num:nums[x]
                            ,pic:pics[x]
                        };
                    }
                }else{
                    for(var x in carnums){
                        carnums[x] = Number(carnums[x]);
                    }
                }
                var sql1 = "select carnum.id,num,carbrand from carnum LEFT JOIN carbrand on cbid=carbrand.id where carnum.id in (?)";
                var args1 = [carnums];
                conn.query(sql1 ,args1 ,function(err ,rows){
                    conn.release();
                    if(err){
                        debug(err)
                    }else{
                        if(data.type == 1){
                            for(var x in rows){
                                var car = rows[x];
                                for(var y in carList){
                                    if(carList[y].carnum == car.id){
                                        carList[y].type=car.num;
                                        carList[y].brand=car.carbrand;
                                    }
                                }
                            }
                        }

                        var order = {
                            id:data.id,orderno:data.orderno,type:data.type,cars:carList,carnums:carnums,nums:nums,total:count,picpath:data.picpath
                            ,from:data.startstation,dest:data.endstation,bstart:data.starttime,bend:data.endtime
                            ,username:data.username,phone:data.phone,status:data.status,createtime:data.createtime,price:data.price
                            ,advicestate:data.advicestate,accept:data.accept

                            ,user:{id:data.userid,phone:data.uphone,headerpath:data.uheaderpath}

                            ,carrier:{id:data.carrierid,phone:data.cphone,company:data.ccompany,headerpath:data.cheaderpath,createtime:data.ccreatetime
                                ,carrierauthstate:data.carrierauthstate,address:data.address,introduce:data.introduce,licences:data.licences,roadlicences:data.roadlicences
                                ,attitude:data.cattitude,care:data.ccare,corresponds:data.ccorresponds,evaluationnum:data.evaluationnum
                            }
                            ,comment:{
                                inforid:data.id,attitude:data.attitude,care:data.care,corresponds:data.corresponds
                                ,evaluation:data.evaluation,createtime:data.ecreatetime
                            }
                        }
                        callback(null ,order);
                    }
                })
            }
        })
    })
}
